from django.contrib.auth.models import User, AbstractUser
from django.db import models
from django.core.validators import RegexValidator
from django.conf import settings
from django.dispatch import receiver
from django.db.models.signals import pre_save
class CustomUser(AbstractUser):
    email = models.EmailField(unique=True, db_index=True, verbose_name="邮箱")
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True, verbose_name='头像')
    bio = models.TextField(null=True, blank=True, verbose_name='个人简介')
    phone_regex = RegexValidator(
        regex=r'^\+?1?\d{9,15}$',
        message="手机号格式: +8613912345678 或 13912345678"
    )
    phone = models.CharField(
        validators=[phone_regex],
        max_length=17,
        unique=True,
        null=True,
        blank=True,
        verbose_name="手机号"
    )
    slug_user = models.CharField(max_length=200,blank=True,null=True, unique=True, verbose_name='url标识')
    # 修复权限系统反向关系冲突
    groups = models.ManyToManyField(
        'auth.Group',
        related_name="custom_user_groups",
        blank=True,
        verbose_name='用户组'
    )
    user_permissions = models.ManyToManyField(
        'auth.Permission',
        related_name="custom_user_permissions",
        blank=True,
        verbose_name='用户权限'
    )
    def __str__(self):
        return self.username

    class Meta:
        db_table = 'user'
        verbose_name = '用户表'
        verbose_name_plural = '用户表'

@receiver(pre_save, sender=CustomUser)
def pre_save_receiver(sender, instance, **kwargs):
    if not instance.slug_user:
        # 使用作者用户名和作者账号创建时间生成slug
        joined_date = instance.date_joined.strftime('%Y%m%d%H%M%S')
        username = instance.username
        instance.slug_user = f"{username}-{joined_date}"

# class Profile(models.Model):
#     """用户模型，扩展Django内置的用户模型"""
#     user = models.OneToOneField(
#         settings.AUTH_USER_MODEL,
#         on_delete=models.CASCADE,
#         related_name='profile',
#     )
#     # 会员相关
#     is_upgrade = models.IntegerField(default=0, verbose_name='是否升级会员')
#     upgrade_time = models.DateTimeField(blank=True, null=True, verbose_name='升级日期')
#     expire_time = models.DateTimeField(blank=True, null=True, verbose_name='过期时间')
#     upgrade_count = models.IntegerField(default=0, verbose_name='升级次数')
#
#     # 关联电影表
#     # movies = models.ManyToManyField(Movie)
#     def __str__(self):
#         return self.user
#
#     class Meta:
#         db_table = 'user_profile'
#         verbose_name = '会员管理'
#         verbose_name_plural = '会员管理'
